#!/usr/bin/env python3
"""
腾讯云一键部署启动脚本
"""
import os
import sys
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 导入应用
from app import app, db

def init_database():
    """初始化数据库"""
    try:
        with app.app_context():
            # 创建所有表
            db.create_all()
            print("✅ 数据库初始化成功")
            
            # 检查是否有数据
            from app import Collection, Category
            collections_count = Collection.query.count()
            categories_count = Category.query.count()
            
            print(f"📊 数据库状态: {collections_count} 个收藏, {categories_count} 个分类")
            
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        sys.exit(1)

def start_server():
    """启动服务器"""
    try:
        # 获取配置
        port = int(os.getenv('PORT', 80))
        host = os.getenv('HOST', '0.0.0.0')
        debug = os.getenv('FLASK_ENV', 'production') == 'development'
        
        print(f"🚀 启动服务器: {host}:{port}")
        print(f"🔧 调试模式: {debug}")
        
        # 启动应用
        app.run(host=host, port=port, debug=debug)
        
    except Exception as e:
        print(f"❌ 服务器启动失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    print("🌟 腾讯云Flask剪藏应用启动中...")
    
    # 初始化数据库
    init_database()
    
    # 启动服务器
    start_server()
